package com.wsg.lightaccounting.Fragment;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.Image;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.wsg.lightaccounting.Activity.MainActivity;
import com.wsg.lightaccounting.Adapter.RecordAdapter;
import com.wsg.lightaccounting.Model.AccountManager;
import com.wsg.lightaccounting.Model.RecordManager;
import com.wsg.lightaccounting.PopupWindow.AccountBookPopupWindow;
import com.wsg.lightaccounting.R;

import org.w3c.dom.Text;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link RecordFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link RecordFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class RecordFragment extends Fragment {
    private ListView record;
    private TextView balace_sum;
    private LinearLayout acccount_choose;
    private ToggleButton isEdit;
    private RecordAdapter recordAdapter;

    public static long account_book_id = 0L;
    public static String UPDATEUI_RECORD_FRAGMENT = "update UI in record_fragment";

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction() == UPDATEUI_RECORD_FRAGMENT){
                updateUI();
                isEdit.setChecked(false);
                RecordAdapter.setIsEdit(isEdit.isChecked());
                recordAdapter.notifyDataSetChanged();
            }
        }
    };
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    public RecordFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment RecordFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static RecordFragment newInstance(String param1, String param2) {
        RecordFragment fragment = new RecordFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(UPDATEUI_RECORD_FRAGMENT);
        getActivity().registerReceiver(broadcastReceiver, intentFilter);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.fragment_record, container, false);
        initView(view);
        return view;
    }

    private void initView(final View view){
        record = (ListView) view.findViewById(R.id.record);
        balace_sum = (TextView) view.findViewById(R.id.balance_sum);
        acccount_choose = (LinearLayout) view.findViewById(R.id.account_choose);
        isEdit = (ToggleButton) view.findViewById(R.id.is_edit);
        recordAdapter = new RecordAdapter(getActivity());

        record.setAdapter(recordAdapter);
        isEdit.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                RecordAdapter.setIsEdit(isChecked);
                updateUI();
            }
        });
        acccount_choose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAccountBookChoose(RecordFragment.this.getActivity(),view);
            }
        });
    }
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        updateUI();
    }

    @Override
    public void onResume() {
        super.onResume();
        updateUI();
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    private void setBalance_sum(){
        String balance = "余额："+String.valueOf(AccountManager.getSum());
        balace_sum.setText(balance);
    }

    private void showAccountBookChoose(Activity context, View view){
        AccountBookPopupWindow accountBookPopupWindow = new AccountBookPopupWindow(context,view.findViewById(R.id.account_choose).getWidth(),
                view.findViewById(R.id.account_choose).getHeight()*3);
        accountBookPopupWindow.showAsDropDown(view.findViewById(R.id.account_choose));
    }
    public void updateUI(){
       recordAdapter.setRecords();
        recordAdapter.notifyDataSetChanged();
        setBalance_sum();
    }

}
